<template>
  <div class="kjk">
    <div class="backDiv" v-if="status == 0">
      <div class="ttt">
        <div class="ztfh">{{ contentTitle }}</div>
      </div>
      <div class="tcxq">套餐详情</div>
      <div class="tcs">
        <div class="benefitsList">
          <img :src="comboPhoto" />
        </div>
        <div class="tcxq2">精选礼品</div>
        <a-flex class="productImages">
          <div class="bc">
            <img src="@/assets/b.png" width="100%" />
          </div>
          <div class="bc">
            <img src="@/assets/a.png" width="100%" />
          </div>
        </a-flex>
      </div>
      <div class="bottomBar">
        <div class="b1">
          <img src="@/assets/200.png" class="img20" />
        </div>
        <div class="b2">
          <img src="@/assets/170.png" class="img20" />
        </div>

        <div class="b3">
          ￥ <span class="num">{{ comboMealAmount }}</span>
        </div>
        <div @click="handleClick" class="b4">立即办理</div>
      </div>
      <Menu />
    </div>
    <div v-else class="membership-page">
      <div class="kkk" @click="goUser">
        <a-flex class="tt">
          <van-image
            round
            class="img48"
            :src="userInfo?.memberPicture ? userInfo?.memberPicture : tx"
          />
          <a-flex class="pn">
            <div v-if="userInfo?.phonenumber != null">
              {{
                userInfo?.phonenumber.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
              }}
            </div>
            <div>{{ userInfo?.memberName }}</div>
          </a-flex>
        </a-flex>
      </div>

      <div class="xm">
        <div class="membership-card">
          <div class="card-header">
            <div class="card-title">
              <img src="@/assets/39.png" class="img24" />
              {{ userInfo?.memberLevel }}
            </div>
            <div class="usage-details" @click="goBillDetails">
              使用明细
              <van-icon name="arrow" />
            </div>
          </div>
          <div class="box_7">
            <span class="text_10">{{
              userInfo?.accountBalance == null ? 0 : userInfo?.accountBalance
            }}</span>
            <div class="text-wrapper_5">
              <span class="text_11">余额</span>
              <span class="text_12" v-if="userInfo?.memberEndDate == null"
                >终生会员</span
              >
              <span class="text_12" v-else
                >{{ userInfo?.memberEndDate
                }}{{ validity == true ? '到期' : '已过期' }}</span
              >
            </div>
          </div>
        </div>

        <div class="benefits-section">
          <div class="section-header">
            <img src="@/assets/28.png" class="img24" />
            我的权益
          </div>

          <div
            class="benefit-item"
            v-for="(item, index) in qyList"
            :key="index"
          >
            <div class="benefit-content">
              <div class="benefit-title">
                {{ item.raiName }}
              </div>
              <div class="validity-period" v-if="item.intervalNum == 0">
                {{ userInfo?.memberBeginDate }}—{{
                  userInfo?.memberEndDate
                }}过期失效
              </div>
              <div class="validity-period" v-else>
                {{ item.beginDate }} — {{ item.endDate }}
              </div>
              <div class="view-details" @click="goEquity(item)">
                查看使用明细
                <van-icon name="arrow" />
              </div>
            </div>
            <div v-if="item.intervalNum == 0 || item.overdue == true">
              <div
                class="claimButton waiting"
                @click="goChooseRights(item)"
                v-if="item.getStatus == 0"
              >
                待领取
              </div>
              <div class="claimButton waitings" @click="goChooseRights(item)" v-else>
                已领取
              </div>
            </div>
          </div>
        </div>
      </div>
      <Menu />
      <Receive :show="showReceive" @closeShow="closeShow" :qyRow="qyRow" />
    </div>

    <van-popup v-model:show="show" position="bottom" class="popup">
      <div class="w">
        <div class="e">{{ raiDetail.raiName }}</div>
        <div class="num">该权益已全部领取</div>
      </div>

      <van-button type="default" block class="copy-button" @click="goEquity(qyi)">
        查看使用明细</van-button
      >
    </van-popup>
  </div>
</template>

<script setup>
import { isWeChatBrowser, formatDateTime } from '@/utils/util'
import { useRouter } from 'vue-router'
import md5 from 'md5'
import {
  raiList,
  goodsRaiList,
  orderRaiList,
  putSystemMember,
  payWechatPay,
  systemSetMenu,
  mealList,
  addOrder,
  getSystemMemberInfo,
} from '@/api/api'
import Menu from '@/components/menus/index.vue'
import UserInfo from '@/components/userInfo/index.vue'
import Receive from './receive.vue'
import wx from 'weixin-jsapi'
import p146 from '@/assets/146.png'
import tx from '@/assets/129.png'
import { Toast } from 'vant'
import { useAppStore } from '@/store'
const appStore = useAppStore()
const router = useRouter()

const qyList = ref([])
const qyRow = ref({})
const status = ref(0)
const show = ref(false)
const qyi = ref(null)
const showReceive = ref(false)
const userInfo = ref({})
const raiDetail = ref({})
const comboMealAmount = ref(0)
const comboPhoto = ref('')
const contentTitle = ref('')
const validity = computed(() => {
  if (!userInfo.value?.memberEndDate) return false
  const endDate = new Date(userInfo.value?.memberEndDate)
  const now = new Date()
  return endDate > now
})

onBeforeMount(() => {
  getMealList()
  userInfo.value = JSON.parse(localStorage.getItem('userInfo'))
  console.log('userInfo.value:vip ', userInfo.value)

  if (userInfo.value == null) {
    status.value = 0
  } else {
    status.value = userInfo.value?.status
  }
  if (status.value == 1) {
    getList()
  }
})

const goUser = () => {
  router.push({ path: '/my' })
}
// 获取套餐金额
const getMealList = () => {
  mealList().then((res) => {
    if (res.code == 200) {
      comboMealAmount.value = res.data[0]?.comboMealAmount
      comboPhoto.value = res.data[0]?.comboPhoto
      contentTitle.value = res.data[0]?.comboMealName
    }
  })
}
const getList = async () => {
  const res = await raiList({
    raiStatus: 1,
    phonenumber: userInfo.value?.phonenumber,
  })
  if (res.code == 200) {
    res.rows.forEach((i) => {
      i.beginDate = expireDate(i.intervalNum, i.raiAvailableNum).beginDate
      i.endDate = expireDate(i.intervalNum, i.raiAvailableNum).endDate
      i.overdue = validity2(i.endDate)
    })
    qyList.value = res.rows
  }
}

const goBillDetails = () => {
  router.push({ path: '/billDetails' })
}
const goEquity = (v) => {
  router.push({ path: '/equity', query: { id: v.id } })
}
const goChooseRights = (v) => {
  console.log('v: ', v)
  raiDetail.value = v
  if (v.getStatus == 0) {
    let num = v.raiGoodsParam.slice(1, -1).split(',')
    if (num.length == 1) {
      showReceive.value = true
      qyRow.value = v
      console.log('qyRow.value: ', qyRow.value)
    } else {
      router.push({
        path: '/chooseRights',
        query: {
          raiGoodsParam: v.raiGoodsParam,
          qyRow: JSON.stringify(v),
          raiOrderNum: v.raiNum,
        },
      })
    }
  } else {
    let p = {
      memberId: userInfo.value.id,
      memberName: userInfo.value.memberName,
      raiId: v.id, //权益ID
      raiName: qyRow.raiName, //权益名称
      payment: 0,
      goodsId: '',
      raiOrderNum: v.raiNum, //权益数量
    }
    addOrder(p).then((res) => {
      if (res.code != 200) {
        Toast.fail(res.msg)
      }
    })
  }
}
const closeShow = () => {
  showReceive.value = false
}
const handleClick = async () => {
  if (userInfo.value?.phonenumber == null) {
    router.push({ path: '/login' })
    return
  }

  if (isWeChatBrowser()) {
    payWithWeChatJSAPI()
  } else {
    // 网页支付
  }
}

// ======================== 微信内支付（JS-SDK） ========================
const payWithWeChatJSAPI = () => {
  payWechatPay({
    openid: userInfo.value.openId || '',
    memberId: userInfo.value.id,
  }).then((res) => {
    if (res.code == 200) {
      // 1. 准备支付参数
      const timeStamp = Math.floor(Date.now() / 1000).toString()
      const { appid, nonceStr, prepayId } = res.data

      // 2. 计算paySign
      const pack = `prepay_id=${prepayId}`
      const signType = 'MD5'
      const signStr = `appId=${appid}&nonceStr=${nonceStr}&package=${pack}&signType=${signType}&timeStamp=${timeStamp}&key=242ae05df692455dbb912f3ed250dc2b`
      const paySign = md5(signStr).toUpperCase()

      let payParams = {
        appId: appid,
        timeStamp: timeStamp,
        nonceStr: nonceStr,
        package: pack,
        signType: signType,
        paySign: paySign,
      }
      WeixinJSBridge.invoke('getBrandWCPayRequest', payParams, (res) => {
        console.log('res: ', res)
        if (res.err_msg === 'get_brand_wcpay_request:ok') {
          putSystemMember({ id: userInfo.value.id, status: 1 }).then((res1) => {
            if (res1.code == 200) {
              getSystemMemberInfo(userInfo.value.id).then((res) => {
                if (res.code == 200) {
                  localStorage.setItem('userInfo', JSON.stringify(res.data))

                  window.location.href = 'https://h5.tonghuajiankang.com/my'
                }
              })
            }
          })
        } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
          Toast.fail('取消支付')
        } else {
          Toast.fail('支付失败')
        }
      })
    }
  })
}

const expireDate = (num, raiAvailableNum) => {
  if (!userInfo.value?.memberBeginDate) return ''

  const beginDate = new Date(userInfo.value.memberBeginDate)
  const now = new Date() // 使用当前真实时间

  // 计算基于raiAvailableNum的最大结束日期
  const maxEndDateByAvailableNum = new Date(
    beginDate.getTime() + raiAvailableNum * num * 24 * 60 * 60 * 1000
  )

  // 如果最大可用结束日期已经小于当前时间
  if (now > maxEndDateByAvailableNum) {
    // 计算最后一个周期的开始和结束时间
    const lastPeriodBeginDate = new Date(
      maxEndDateByAvailableNum.getTime() - num * 24 * 60 * 60 * 1000
    )
    return {
      beginDate: formatDateTime(lastPeriodBeginDate),
      endDate: formatDateTime(maxEndDateByAvailableNum),
    }
  }

  // 计算理论结束日期（加上num天）
  const calculatedEndDate = new Date(
    beginDate.getTime() + num * 24 * 60 * 60 * 1000
  )

  // 确定最终的结束日期（取calculatedEndDate和maxEndDateByAvailableNum中较小的一个）
  const finalEndDate =
    calculatedEndDate > maxEndDateByAvailableNum
      ? maxEndDateByAvailableNum
      : calculatedEndDate

  // 如果当前时间已超过最终结束日期
  if (now > finalEndDate) {
    // 计算已经过了多少个num天周期
    const timeDiff = now.getTime() - beginDate.getTime()
    const numOfPeriods = Math.floor(timeDiff / (num * 24 * 60 * 60 * 1000))

    // 计算新的开始和结束时间
    const newBeginDate = new Date(
      beginDate.getTime() + numOfPeriods * num * 24 * 60 * 60 * 1000
    )
    const newEndDate = new Date(
      newBeginDate.getTime() + num * 24 * 60 * 60 * 1000
    )

    // 确保新的结束日期不超过最大可用次数限制
    const adjustedNewEndDate =
      newEndDate > maxEndDateByAvailableNum
        ? maxEndDateByAvailableNum
        : newEndDate

    return {
      beginDate: formatDateTime(newBeginDate),
      endDate: formatDateTime(adjustedNewEndDate),
    }
  }

  // 如果当前时间未超过最终结束日期，返回原始时间范围
  return {
    beginDate: formatDateTime(beginDate),
    endDate: formatDateTime(finalEndDate),
  }
}
const validity2 = (v) => {
  const endDate = new Date(v)
  const now = new Date()
  return endDate > now
}
</script>
<style scoped lang='less'>
.kjk {
  background: #fcfaf4;
  overflow: hidden;
  height: 100vh;

  .header {
    text-align: center;
    margin: 0;
    padding: 10px;
    border-bottom: 1px solid #ccc;
  }
}

.popup {
  height: 30%;

  .w {
    font-size: 20px;
    font-weight: bold;
    padding: 10px;
  }

  .e {
    margin-bottom: 10px;
  }
}

.num {
  font-size: 20px;
  font-weight: bold;
  color: #ff6657;
}
.membership-page {
  height: calc(100vh - 60px);
  position: relative;
  .kkk {
    width: 100%;
    height: 24vh;
    background: url(@/assets/140.png) no-repeat;
    background-size: 100% 100%;
    .tt {
      height: 13vh;
      display: flex;
      align-items: center;
      margin-left: 6%;
      .pn {
        flex-direction: column;
        margin-left: 12px;
        color: #fff;
        font-size: 16px;
      }
    }
  }

  .xm {
    width: 95%;
    margin: -2rem auto;
    height: calc(100vh - 161px);
    .membership-card {
      width: 100%;
      background: url(@/assets/132.png) no-repeat;
      background-size: 100% 100%;
      padding: 0.5rem;
      .box_7 {
        width: 184px;
        margin: 17px 125px 0 0;
        display: flex;
        flex-direction: row;
        .text_10 {
          overflow-wrap: break-word;
          color: rgba(109, 70, 21, 0.85);
          font-size: 40px;
          letter-spacing: -0.8000002503395081px;
          font-family: Roboto-Bold;
          font-weight: 700;
          text-align: center;
          white-space: nowrap;
          line-height: 47px;
        }
        .text-wrapper_5 {
          margin: 11px 0 7px 10px;
          display: flex;
          align-items: flex-start;
          flex-direction: column;
          .text_11 {
            overflow-wrap: break-word;
            color: rgba(109, 70, 21, 0.5);
            font-size: 12px;
            letter-spacing: -0.24000006914138794px;
            font-weight: normal;
            text-align: center;
            white-space: nowrap;
            line-height: 17px;
            margin-right: 62px;
          }
          .text_12 {
            overflow-wrap: break-word;
            color: rgba(109, 70, 21, 0.5);
            font-size: 12px;
            letter-spacing: -0.24000006914138794px;
            font-weight: normal;
            text-align: center;
            white-space: nowrap;
            line-height: 17px;
          }
        }
      }
    }
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.card-title {
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 14px;
  color: rgba(109, 70, 21, 0.85);
  line-height: 20px;
  text-align: left;
  font-style: normal;
}

.usage-details {
  font-size: 14px;
  display: flex;
  align-items: center;
  color: rgba(109, 70, 21, 0.85);
}

.benefits-section {
  padding: 16px;
  height: calc(100vh - 7rem);
  overflow-y: auto;
}

.section-header {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  color: #333;
}

.benefit-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #ffffff;
  box-shadow: 0px 6px 10px 0px rgba(75, 38, 0, 0.06);
  border-radius: 12px;
  margin-bottom: 12px;
}

.benefit-item:last-child {
  border-bottom: none;
}

.benefit-title {
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 16px;
  color: #34373b;
  line-height: 22px;
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 限制显示两行 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.validity-period {
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.5);
  line-height: 20px;
  text-align: left;
  font-style: normal;
  margin-top: 26px;
}

.view-details {
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: rgba(109, 70, 21, 0.85);
  line-height: 20px;
  font-style: normal;
  width: 110px;
}

.claimButton {
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  white-space: nowrap;
}

.waiting {
  background-color: #e8c48e;
  color: white;
}
.waitings {
  background-color: rgba(249, 217, 170, 0.24);
  color: rgba(216, 176, 117, 1);
  border: 1px solid rgba(216, 176, 117, 1);
}

.benefit-content {
  flex: 1;
  padding-right: 16px;
}

.backDiv {
  width: 100vw;
  height: calc(100vh - 60px);
  // background: url(@/assets/147.png) no-repeat;
  // background-size: 100% 100%;
  position: relative;
  .ttt {
    height: 18vh;
    background: url(@/assets/201.png) no-repeat;
    background-size: 100% 100%;
    position: relative;
    .ztfh {
      // padding-top: 4vh;
      width: 30%;
      // height: 18vh;
      font-size: 26px;
      font-weight: bold;
      color: #d4af37;
      text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
      word-break: break-all;

      // margin-left: 12%;
      position: absolute;
      top: 50%;
      left: 25%;
      transform: translate(-50%, -50%);
    }
  }
  .tcxq {
    font-weight: bold;
    font-size: 18px;
    color: #623e26;
    position: absolute;
    top: 15.5vh;
    left: 50%;
    transform: translateX(-50%);
  }
  .tcs {
    text-align: center;
    font-weight: bold;
    overflow-y: auto;
    height: calc(100vh - 18vh - 60px);
    background: url(@/assets/203.png) no-repeat;
    background-size: 100% 100%;
    padding-top: 2%;
    .benefitsList {
      padding: 0 8vw;
      overflow: hidden;
      margin: 0 auto;
      display: flex;
      height: calc(100vh - 20vh - 38vh);
      border-radius: 10px;
      img {
        width: 100%;
      }
    }
    .tcxq2 {
      height: 5vh;
      line-height: 5vh;
      font-weight: bold;
      font-size: 18px;
      color: #623e26;
    }
    .productImages {
      height: 17vh;
      padding: 0 8vw;
      overflow: hidden;
      justify-content: space-between;
      display: flex;
      width: 100%;
      .bc {
        width: 45%;
        border-radius: 10px;
        overflow: hidden;
      }
    }
  }
  .bottomBar {
    width: 90%;
    height: 5vh;
    position: absolute;
    display: flex;
    bottom: 1vh;
    left: 50%;
    transform: translateX(-50%);
    background: #fff;
    border-radius: 51px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .b1 {
      width: 20%;
      margin-left: -2%;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .b2 {
      width: 10%;
      margin-top: -2%;
      img {
        width: 24px;
        height: 24px;
      }
    }
    .b3 {
      width: 40%;
      color: #6d4615;
      font-size: 16px;
      font-family: PingFangSC-Medium;
      .num {
        color: #6d4615;
        font-size: 26px;
      }
    }
    .b4 {
      width: 30%;
      height: 4vh;
      background: url(@/assets/202.png) no-repeat;
      background-size: 100% 100%;
      font-size: 16px;
      font-family: PingFangSC-Medium;
      color: #6d4615;
      text-align: center;
      margin-right: 5px;
      line-height: 4vh;
    }
  }
}
</style>